package com.yycx.module.bus.provider.handler.process.task;

import com.yycx.bpm.provider.listener.FlowPageInterceptor;
import com.yycx.bpm.provider.model.TaskResponse;
import com.yycx.bpm.provider.service.impl.FlowableTaskServiceImpl;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.DateUtils;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.module.admin.client.entity.BaseUser;
import com.yycx.module.admin.provider.service.BaseUserService;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.enums.AmountTypeEnum;
import com.yycx.module.bus.provider.service.*;
import org.flowable.common.engine.api.query.Query;
import org.flowable.engine.RuntimeService;
import org.flowable.task.api.TaskInfoQuery;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 资金支付审批任务列表
 *
 * @author zyf
 */
@Component
public class PaymentTaskTodoListHandler implements FlowPageInterceptor<TaskResponse> {

    @Autowired
    private BusPaymentService paymentService;
    @Autowired
    private BusSupplierBankService supplierBankService;
    @Autowired
    private BusSupplierService supplierService;

    @Autowired
    private BusDeptService deptService;

    @Autowired
    private BusCustomService customService;
    @Autowired
    private BaseUserService userService;
    @Autowired
    private BusOrderService orderService;
    @Autowired
    private BusSalemanService salemanService;

    @Autowired
    private BusInvoiceunitService invoiceunitService;

    @Autowired
    private BusSalemanBankService salemanBankService;

    @Autowired
    private BusInvoiceunitBankService invoiceunitBankService;

    @Autowired
    private BusDrugsPlanService drugsPlanService;

    @Autowired
    protected RuntimeService runtimeService;

    @Override
    public void prepare(Query query, EntityMap params) {
        TaskInfoQuery taskQuery = (TaskInfoQuery) query;
        String companyId=OpenHelper.getCompanyId().toString();
        String paymentNo = params.get("paymentNo");
        String deptId = params.get("deptId");
        String supplierId = params.get("supplierId");
        String customId = params.get("customId");
        String amountType = params.get("amountType");
        String taskName = params.get("taskName");
        String linkMan = params.get("linkMan");
        BusPayment payment = paymentService.getByProperty("paymentNo", paymentNo);
        if (FlymeUtils.isNotEmpty(payment)) {
            taskQuery.processInstanceBusinessKey(payment.getPaymentId().toString());
        } else {
            if(FlymeUtils.isNotEmpty(paymentNo)) {
                taskQuery.processVariableValueLike("paymentNo",'%'+paymentNo);
            }
        }
        if(FlymeUtils.isNotEmpty(amountType)) {
            taskQuery.processVariableValueEquals("amountType", amountType);
        }
        if(FlymeUtils.isNotEmpty(deptId)) {
            taskQuery.processVariableValueEquals("deptId", Long.parseLong(deptId));
        }
        if(FlymeUtils.isNotEmpty(linkMan)) {
            taskQuery.processVariableValueLike("linkMan",linkMan);
        }
        if(FlymeUtils.isNotEmpty(supplierId)) {
            taskQuery.processVariableValueEquals("supplierId", Long.parseLong(supplierId));
        }
        if(FlymeUtils.isNotEmpty(customId)) {
            taskQuery.processVariableValueEquals("customId", Long.parseLong(customId));
        }
        if(FlymeUtils.isNotEmpty(taskName)) {
            taskQuery.taskName(taskName);
        }
        taskQuery.taskTenantId(companyId);
        taskQuery.processDefinitionKey("payment_pay_"+companyId);
    }

    @Override
    public List<EntityMap> complete(Query query, List<TaskResponse> data, EntityMap params) {
        List<EntityMap> list = new ArrayList<>();
        if (FlymeUtils.isNotEmpty(data)) {
            for (TaskResponse taskResponse : data) {
                EntityMap map = new EntityMap();
                map.put("processInstanceId", taskResponse.getProcessInstanceId());
                String paymentId = taskResponse.getBusinessKey();
                if (FlymeUtils.isNotEmpty(paymentId)) {
                    BusPayment payment = paymentService.getById(paymentId);
                    if (FlymeUtils.isNotEmpty(payment)) {
                        Long userId = payment.getUserId();
                        Long deptId = payment.getDeptId();
                        String customId=payment.getCustomId();
                        Long supplierId=payment.getSupplierId();
                        if (FlymeUtils.isNotEmpty(deptId)) {
                            BusDept dept = deptService.getById(deptId);
                            map.put("deptName", dept.getDeptName());
                            map.put("saleManId", dept.getSalemanId());
                        }
                        if(FlymeUtils.isNotEmpty(customId)){
                            BusCustom custom = customService.getById(customId);
                            map.put("customName", custom.getCustomName());
                        }
                        if(FlymeUtils.isNotEmpty(supplierId)){
                            BusSupplier supplier = supplierService.getById(supplierId);
                            if(FlymeUtils.isNotEmpty(supplier)) {
                                map.put("supplierName", supplier.getSupplierName());
                            }
                        }
                        //单据类型
                        String amountType = payment.getAmountType();
                        BaseUser user = userService.getById(userId);
                        //垫付款
                        if (AmountTypeEnum.SupplierBond.getCode().equals(amountType)) {
                            getSupplierBondMap(payment, map);
                        }
                        //开票税金
                        if (AmountTypeEnum.Invoice.getCode().equals(amountType)) {
                            getInvoiceMap(payment, map);
                        }
                        //结算单
                        if (AmountTypeEnum.Settle.getCode().equals(amountType) || AmountTypeEnum.CbReturn.getCode().equals(amountType)) {
                            getSettleMap(payment, map);
                        }

                        map.put("paymentNo", payment.getPaymentNo());
                        map.put("paymentId", payment.getPaymentId());
                        map.put("amountType", amountType);
                        map.put("amount", payment.getAmount());
                        if(FlymeUtils.isNotEmpty(user)) {
                            map.put("nickName", user.getNickName());
                        }
                        map.put("createTime", payment.getCreateTime());
                        map.put("amountDate", DateUtils.formatDate(payment.getAmountDate(), "yyyy-MM-dd"));
                        map.put("paymentState", payment.getPaymentState());
                        map.put("assignee", taskResponse.getAssignee());

                        map.put("taskName", taskResponse.getName());
                        map.put("taskId", taskResponse.getId());
                        map.put("endTime", taskResponse.getEndTime());
                        map.put("orderId", payment.getOrderId());
                        //采购流程
                        if("DrugsPlan".equals(amountType)){
                            getDrugsPlanMap(payment,map);
                        }

                    }
                    list.add(map);
                }
            }
        }
        return list;
    }

    /**
     * 查询垫付款信息
     *
     * @param payment
     * @param map
     */
    private void getSupplierBondMap(BusPayment payment, EntityMap map) {
        Long supplierId = payment.getSupplierId();
        String customId = payment.getCustomId();
        String orderId = payment.getOrderId();
        BusSupplier supplier = supplierService.getById(supplierId);
        BusCustom custom = customService.getById(customId);
        BusOrder order = orderService.getById(orderId);
        //收款银行ID
        Long bankId = payment.getBankId();
        BusSupplierBank supplierBank = supplierBankService.getById(bankId);
        map.put("bankName", supplierBank.getBankName());
        map.put("bankNo", supplierBank.getBankNo());
        map.put("supplierBondType", order.getSupplierBondType());
        map.put("unitName", supplier.getSupplierName());
        map.put("linkMan", supplierBank.getLinkMan());
        String id=map.get("processInstanceId");
        VariableInstance variableInstance=runtimeService.getVariableInstance(id,"linkMan");
        if(FlymeUtils.isEmpty(variableInstance)){
            runtimeService.setVariable(id,"linkMan",supplierBank.getLinkMan());
        }
        map.put("customName", custom.getCustomName());
        map.put("supplierName", supplier.getSupplierName());
        map.put("orderNo", order.getOrderNo());
    }

    /**
     * 查询药品采购信息
     *
     * @param payment
     * @param map
     */
    private void getDrugsPlanMap(BusPayment payment, EntityMap map) {

        String orderId = payment.getOrderId();
        BusDrugsPlan drugsPlan = drugsPlanService.getById(orderId);
        //收款银行ID
        Long bankId = payment.getBankId();
        map.put("bankName", drugsPlan.getBank());
        map.put("bankNo", drugsPlan.getBankNo());
        map.put("unitName", drugsPlan.getReceivingUnit());
    }

    /**
     * 查询开票税金信息
     *
     * @param payment
     * @param map
     */
    private void getInvoiceMap(BusPayment payment, EntityMap map) {
        Long invoiceUnitId = payment.getInvoiceUnitId();
        BusInvoiceunit invoiceunit = invoiceunitService.getById(invoiceUnitId);
        Long bankId = payment.getBankId();
        BusInvoiceunitBank invoiceunitBank = invoiceunitBankService.getById(bankId);
        if (FlymeUtils.isNotEmpty(invoiceunit)) {
            map.put("unitName", invoiceunit.getInvoiceunitName());
        }
        if (FlymeUtils.isNotEmpty(invoiceunitBank)) {
            map.put("linkMan", invoiceunitBank.getLinkMan());
            String id=map.get("processInstanceId");
            VariableInstance variableInstance=runtimeService.getVariableInstance(id,"linkMan");
            if(FlymeUtils.isEmpty(variableInstance)){
                runtimeService.setVariable(id,"linkMan",invoiceunitBank.getLinkMan());
            }
        }
    }

    /**
     * 查询结算单信息
     *
     * @param payment
     * @param map
     */
    private void getSettleMap(BusPayment payment, EntityMap map) {
        Long saleManId = map.getLong("saleManId");
        Long bankId = payment.getBankId();
        if (FlymeUtils.isNotEmpty(bankId)) {
            //收款人
            BusSalemanBank salemanBank = salemanBankService.getById(bankId);
            Long smanId = salemanBank.getSaleManId();
            BusSaleman skr = salemanService.getById(smanId);
            map.put("linkMan", skr.getSaleManName());
            String id=map.get("processInstanceId");
            VariableInstance variableInstance=runtimeService.getVariableInstance(id,"linkMan");
            if(FlymeUtils.isEmpty(variableInstance)){
                runtimeService.setVariable(id,"linkMan",skr.getSaleManName());
            }
        }
        if (FlymeUtils.isNotEmpty(saleManId)) {
            //收款单位
            BusSaleman busSaleman = salemanService.getById(saleManId);
            map.put("unitName", busSaleman.getSaleManName());
        }
    }
}
